package com.tianji.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.api.client.course.CatalogueClient;
import com.tianji.api.client.course.CourseClient;
import com.tianji.api.dto.IdAndNumDTO;
import com.tianji.api.dto.course.CataSimpleInfoDTO;
import com.tianji.api.dto.course.CourseFullInfoDTO;
import com.tianji.api.dto.course.CourseSimpleInfoDTO;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.domain.query.PageQuery;
import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.DateUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.LearningPlanDTO;
import com.tianji.learning.domain.po.LearningLesson;
import com.tianji.learning.domain.po.LearningRecord;
import com.tianji.learning.domain.vo.LearningLessonVO;
import com.tianji.learning.domain.vo.LearningPlanPageVO;
import com.tianji.learning.domain.vo.LearningPlanVO;
import com.tianji.learning.enums.LessonStatus;
import com.tianji.learning.enums.PlanStatus;
import com.tianji.learning.mapper.LearningLessonMapper;
import com.tianji.learning.mapper.LearningRecordMapper;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 学生课程表 服务实现类
 * </p>
 *
 * @author zjr
 * @since 2024-12-24
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LearningLessonServiceImpl extends ServiceImpl<LearningLessonMapper, LearningLesson> implements ILearningLessonService {

    private final CourseClient courseClient;
    private final LearningRecordMapper recordMapper;

    private final CatalogueClient catalogueClient;
    @Override
    public void addUserLesson(Long userId, List<Long> courseIds) {
        // 1. 通过feign远程调用课程服务，得到课程信息
        List<CourseSimpleInfoDTO> courseInfoList = courseClient.getSimpleInfoList(courseIds);

        // 2. 封装po实体类，填充过期时间
        List<LearningLesson> list = new ArrayList<>();
        for (CourseSimpleInfoDTO courseInfoDTO : courseInfoList) {
            LearningLesson lesson = new LearningLesson();
            lesson.setUserId(userId);
            lesson.setCourseId(courseInfoDTO.getId());
            Integer validDuration = courseInfoDTO.getValidDuration();  // 课程有效期  单位月
            if(validDuration != null){
                LocalDateTime now = LocalDateTime.now();
                lesson.setCreateTime(now);
                lesson.setExpireTime(now.plusMonths(validDuration));
            }
            list.add(lesson);
        }
        // 3. 批量保存
        this.saveBatch(list);
    }

    @Override
    public PageDTO<LearningLessonVO> queryMyLessons(PageQuery query) {
        // 1. 获取当前登录对象
        Long userId = UserContext.getUser();
        if(userId == null){
            throw new BadRequestException("必须得登录");
        }
        // 2. 分页查询我的页表
        Page<LearningLesson> page = this.lambdaQuery()
                .eq(LearningLesson::getUserId, userId)
                .page(query.toMpPage("latest_learn_time", false));
        List<LearningLesson> records = page.getRecords();
        if(CollUtils.isEmpty(records)) {
            return PageDTO.empty(page);
        }
        // 3. 远程调用课程服务，给vo中的课程名 封面 章节数赋值
        List<Long> courseIds = records.stream().map(LearningLesson::getCourseId).collect(Collectors.toList());
        List<CourseSimpleInfoDTO> cinfos = courseClient.getSimpleInfoList(courseIds);
        if(CollUtils.isEmpty(cinfos)){
            throw  new BizIllegalException("课程不存在");
        }

        // 将cinfos课成绩和转换为map结构 <课程id，课程对象>
        Map<Long, CourseSimpleInfoDTO> infoDTOMap = cinfos.stream().collect(Collectors.toMap(CourseSimpleInfoDTO::getId, c -> c));

        // 4. 将po中的数据，封装到vo
        List<LearningLessonVO> voList = new ArrayList<>();
        for (LearningLesson record : records) {
            LearningLessonVO vo = BeanUtils.copyBean(record, LearningLessonVO.class);
            CourseSimpleInfoDTO infoDTO = infoDTOMap.get(record.getCourseId());
            if(infoDTO != null){
                vo.setCourseName(infoDTO.getName());
                vo.setCourseCoverUrl(infoDTO.getCoverUrl());
                vo.setSections(infoDTO.getSectionNum());
            }
            voList.add(vo);
        }
        // 5. 返回
        return PageDTO.of(page, voList);
    }

    @Override
    public LearningLessonVO queryMyCurrentLesson() {
        // 1. 获取当前用户id
        Long userId = UserContext.getUser();
        // 2. 查询当前用户最近学习课程  按latest_learn_time降序排序，取第一条  正在学习中的 status=1
        // sql: select * from learning_lesson where user_Id=xxx and status=1 order by latest_learn_time desc limit 1
        LearningLesson lesson = this.lambdaQuery()
                .eq(LearningLesson::getUserId, userId)
                .eq(LearningLesson::getStatus, LessonStatus.LEARNING)
                .orderByDesc(LearningLesson::getLatestLearnTime)
                .last("limit 1")
                .one();
        if(lesson == null) {
            return null;
        }
        // 3. 远程调用课程服务，给vo中的课程名 封面 章节数赋值
        CourseFullInfoDTO cinfo = courseClient.getCourseInfoById(lesson.getCourseId(), false, false);
        if(cinfo == null){
            throw new BizIllegalException("课程不存在");
        }
        // 4. 查询当前用户课表中 总的课程数
        Integer count = this.lambdaQuery()
                .eq(LearningLesson::getUserId, userId)
                .count();
        // 5. 远程调用课程服务，获取小节名称 小节编号
        Long latestSectionId = lesson.getLatestSectionId(); // 最近学习的小节id
        List<CataSimpleInfoDTO> cataSimpleInfoDTOS = catalogueClient.batchQueryCatalogue(CollUtils.singletonList(latestSectionId));
        if(CollUtils.isEmpty(cataSimpleInfoDTOS)){
            throw new BizIllegalException("小节不存在");
        }
        // 6. 封装到vo返回
        LearningLessonVO vo = BeanUtils.copyBean(lesson, LearningLessonVO.class);
        vo.setCourseName(cinfo.getName());
        vo.setCourseCoverUrl(cinfo.getCoverUrl());
        vo.setSections(cinfo.getSectionNum());
        vo.setCourseAmount(count);       // 当前用户能学习的课程总数
        CataSimpleInfoDTO cataSimpleInfoDTO = cataSimpleInfoDTOS.get(0);
        vo.setLatestSectionName(cataSimpleInfoDTO.getName());  // 最近学习的小节名称
        vo.setLatestSectionIndex(cataSimpleInfoDTO.getCIndex()); // 最近学习的小节序号
        return vo;
    }

    @Override
    public Long isLessonValid(Long courseId) {
        // 1. 获取当前用户信息
        Long userId = UserContext.getUser();
        // 2. 根据用户id查询课表，判断是否有该课程
        LearningLesson lesson = this.lambdaQuery()
                .eq(LearningLesson::getUserId, userId)
                .eq(LearningLesson::getCourseId, courseId)
                .one();
        if(lesson == null) {
            // 2.1 不存在，则直接返回null
            return null;
        }
        // 3. 判断课程是否过期
        LocalDateTime expireTime = lesson.getExpireTime();
        if(expireTime!= null && expireTime.isBefore(LocalDateTime.now())) {
            // 3.1 过期返回null
            return null;
        }
        // 3.2 未过期，返回lessonId
        return lesson.getId();
    }

    @Override
    public LearningLessonVO queryLessonDetail(Long courseId) {
        // 1. 获取当前登录用户信息
        Long userId = UserContext.getUser();
        // 2. 查询用户课表中是否有当前课程
        LearningLesson lesson = this.lambdaQuery()
                .eq(LearningLesson::getUserId, userId)
                .eq(LearningLesson::getCourseId, courseId)
                .one();
        // 3. 若没有，返回null
        if(lesson == null) {
            return null;
        }
        // 4. 若有，返回课程的有效信息
        return BeanUtils.copyBean(lesson, LearningLessonVO.class);
    }

    @Override
    public void deleteUserLesson(Long userId, List<Long> courseIds) {
        log.debug("尝试从用户课表删除课程，用户id：{}，课程id：{}", userId, courseIds);
        if(CollUtils.isEmpty(courseIds)){
            return;
        }
        this.remove(new LambdaQueryWrapper<LearningLesson>()
                .eq(LearningLesson::getUserId, userId)
                .in(LearningLesson::getCourseId, courseIds)
        );
    }

    @Override
    public void createLearningPlan(LearningPlanDTO planDTO) {
        // 1. 获取当前登录id
        Long userId = UserContext.getUser();
        // 2. 查询课表
        LearningLesson lesson = this.lambdaQuery()
                .eq(LearningLesson::getUserId, userId)
                .eq(LearningLesson::getCourseId, planDTO.getCourseId())
                .one();
        if(lesson == null){
            throw new BizIllegalException("该课程没有加入课表");
        }
        // 3. 修改课表
        this.lambdaUpdate()
                .set(LearningLesson::getWeekFreq, planDTO.getFreq())
                .set(lesson.getPlanStatus() == PlanStatus.NO_PLAN, LearningLesson::getPlanStatus, PlanStatus.PLAN_RUNNING)
                .eq(LearningLesson::getId, lesson.getId())
                .update();
    }

    /**
     * 分页查询我的课表
     * @param query 分页参数
     * @return 我的课表
     */
    @Override
    public LearningPlanPageVO queryMyPlans(PageQuery query) {
        // 1. 获取当前登录用户
        Long userId = UserContext.getUser();
        // todo 2. 查询积分

        // 3. 查询本周学习计划总数据 learn_lesson 条件userId status in(0, 1) plan_status=1 查询sum(week_freq)
        QueryWrapper<LearningLesson> wrapper = new QueryWrapper<>();
        wrapper.select("sum(week_freq) as plansTotal");
        wrapper.eq("user_id", userId);
        wrapper.in("status", LessonStatus.NOT_BEGIN, LessonStatus.LEARNING);
        wrapper.eq("plan_status", PlanStatus.PLAN_RUNNING);
        Map<String, Object> map = this.getMap(wrapper);
        int plansTotal = 0;  // 本周学习计划总数
        if(map != null && map.get("plansTotal") != null){
            plansTotal = Integer.parseInt(map.get("plansTotal").toString());
        }
        // 4. 查询本周 实际 已学习的小节总数据 learning_record 条件userId finish_time在本周之内 finished为true count(*)
        LocalDate now = LocalDate.now();
        LocalDateTime weekBeginTime = DateUtils.getWeekBeginTime(now);  // 本周开始时间
        LocalDateTime weekEndTime = DateUtils.getWeekEndTime(now);      // 本周结束时间
        Integer weekFinishedPlanNum = recordMapper.selectCount(Wrappers.<LearningRecord>lambdaQuery()
                .eq(LearningRecord::getUserId, userId)
                .eq(LearningRecord::getFinished, true)
                .between(LearningRecord::getFinishTime, weekBeginTime, weekEndTime));
        // 5. 查询课表数据 learning_lessons 条件 userId status in(0, 1) plan_status=1 分页
        Page<LearningLesson> page = this.lambdaQuery()
                .eq(LearningLesson::getUserId, userId)
                .in(LearningLesson::getStatus, LessonStatus.NOT_BEGIN, LessonStatus.LEARNING)
                .eq(LearningLesson::getPlanStatus, PlanStatus.PLAN_RUNNING)
                .page(query.toMpPage("latest_learn_time", false));
        List<LearningLesson> records = page.getRecords();
        if (CollUtils.isEmpty(records)) {
            LearningPlanPageVO vo = new LearningPlanPageVO();
            vo.setTotal(0L);
            vo.setPages(0L);
            vo.setList(CollUtils.emptyList());
            return vo;
        }
        // 6. 远程调用课程服务，获取课程信息
        Set<Long> courseIds = records.stream().map(LearningLesson::getCourseId).collect(Collectors.toSet());
        List<CourseSimpleInfoDTO> cinfos = courseClient.getSimpleInfoList(courseIds);
        if(CollUtils.isEmpty(cinfos)){
            throw new BizIllegalException("课程不存在");
        }
        // 将cinfos list结构转map <课程id，CourseSimpleInfoDTO>
        Map<Long, CourseSimpleInfoDTO> cinfosMap = cinfos.stream().collect(Collectors.toMap(CourseSimpleInfoDTO::getId, c -> c));
        // 7. 查询学习记录表learning_record 本周 当前用户下 每一门课 已学习的小节数量
//        select lesson_id, count(*) from learning_record
//        where user_id = 2
//        and finished = 1
//        and finish_time between "2023-05-22 00:00:01" and "2023-05-28 23:59:59"
//        group by lesson_id
        List<IdAndNumDTO> idAndNumDTOS = recordMapper.countLearnedSections(userId, weekBeginTime, weekEndTime);
        // map中的key是lessonId，value是当前用户该课程下已经学习的小节数
        Map<Long, Integer> lessonSectionCountMap = IdAndNumDTO.toMap(idAndNumDTOS);

        // 8. 封装vo返回
        LearningPlanPageVO vo = new LearningPlanPageVO();
        vo.setWeekTotalPlan(plansTotal);
        vo.setWeekFinished(weekFinishedPlanNum);

        List<LearningPlanVO> voList = new ArrayList<>();
        for (LearningLesson record : records) {
            LearningPlanVO planVO = BeanUtils.copyBean(record, LearningPlanVO.class);
            CourseSimpleInfoDTO infoDTO = cinfosMap.get(record.getCourseId());
            if(infoDTO != null) {
                planVO.setCourseName(infoDTO.getName()); // 课程名
                planVO.setSections(infoDTO.getSectionNum()); // 课程下的总小节数
            }
            planVO.setWeekLearnedSections(lessonSectionCountMap.getOrDefault(record.getId(), 0));
            voList.add(planVO);
        }
        return vo.pageInfo(page.getTotal(), page.getPages(), voList);
    }
}
